# 异常处理，控制程序非预期情况的执行，增加健壮性
# 基本结构

# try:
#     print('try...')
#     r = 10 / 0
#     print('result:', r)
# except ZeroDivisionError as e:
#     print('except:', e)
# except:
#     print('finally...')
# else:
#     print('END')
# finally:
#     print('finally...')


# try:
#     num = int(input("请输入一个数字:"))
#     result = 10 / num
#     print(result)
# except ZeroDivisionError:
#     print("除数不能为0")
# except ValueError:
#     print("输入值类型错误")
# except Exception as e:
#     print(e)
# finally:
#     print("程序结束")

# 将以上简写

try:
    num = int(input("请输入一个数字:"))
    result = 10 / num
    print(result)
except (ZeroDivisionError, ValueError, Exception) as e:
    print(e)
finally:
    print("程序结束")

## 使用 raise 关键字主动抛出异常; 可以当作对异常的进一步表述
def check_value(a):
    if a <= 0:
        raise ValueError("input value must larger than 0")
    return a

try:
    check_value(-2)
except ValueError:
    raise

## 自定义异常
class MyError(Exception):
    pass
def check_value(a):
    if a <= 0:
        raise MyError("input value must larger than 0")
    return a

try:
    check_value(-2)
except MyError as e:
    print(e)